export default {
  data() {
    return {
      postFollowerData: {} // 职位跟随用户变化
    };
  },
  methods: {
    // 获取当前所变化人员对应的所有职位
    getCurrUserPost(data) {
      let currUserPost = [];
      if (data.isSubTable && data.options.multiple) {
        // 在子表单内部的人员多选对应数据放置于_postValue中
        const userKeys = Object.keys(data && data._postValue || {}).filter(key => !isNaN(Number(key)));
        const allUserPosts = [];
        userKeys.forEach(key => {
          data._postValue[key].post && allUserPosts.push(data._postValue[key].post);
        });
        currUserPost = [...new Set(allUserPosts)];
      } else if (data.options.multiple) {
        currUserPost = [...new Set(data.value.filter(item => item.post).map(item => item.post))];
      } else {
        currUserPost.push(data._post || (data.value && data.value.post));
      }
      return currUserPost;
    },
    // 将当前变更人员对应的职位赋值给所有对应关联的职位组件
    setCurrUserPostToPostField(data, postArr) {
      const currUserPost = this.getCurrUserPost(data);
      const { list } = this.formOptions;
      postArr.forEach(postData => {
        if (postData.isSubTable) {
          const targetSubTable = list.filter(item => item.key === postData.linkFormKey);
          const curSubForm = targetSubTable[0] || {};
          this.$nextTick(() => {
            if (Array.isArray(curSubForm.value) && curSubForm.value.length) {
              const postVal = this.setPostData(postData.isMultiple, currUserPost);
              this.$set(curSubForm.value[data.subformRowIndex || 0], [postData.key], postVal || null);
            }
          });
        } else {
          const outTargetPost = list.filter(item => item.key === postData.key);
          let targetPost = null;
          if (outTargetPost.length) {
            targetPost = outTargetPost[0];
          } else {
            const allGridField = list.filter(item => item.type === 'grid');
            allGridField.forEach(gridField => {
              gridField.columns.forEach(column => {
                column.list.forEach(item => {
                  if (item.key === postData.key) {
                    targetPost = item;
                  }
                });
              });
            });
          }
          const postVal = this.setPostData(postData.isMultiple, currUserPost);
          targetPost && this.$set(targetPost, 'value', postVal || null);
        }
      });
    },
    // 人员多选+职位多选 =》 职位字段全部赋值人员所对应的职位； 人员多选+职位当选 =》 职位字段任选一人员所对应的职位
    setPostData(isMultiple, postList) {
      let postVal = null;
      if (Array.isArray(postList) && postList.length) {
        postVal = postList.filter(name => name).map(name => ({ id: name, name }));
      }
      if (isMultiple) {
        return postVal;
      } else {
        return postVal ? postVal[0] : null;
      }
    }
  }
};
